<?php

namespace app\admin\controller\aps;

use app\common\controller\Backend;
use think\Db;
/**
 * 主制程管理
 *
 * @icon fa fa-circle-o
 */
class Mainprocess extends Backend
{
    
    /**
     * Mainprocess模型对象
     * @var \app\admin\model\aps\Mainprocess
     */
    protected $model = null;
    protected $noNeedRight = ['gstj', 'guanli', 'cpjqyg'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\aps\Mainprocess;
        $this->view->assign("stateList", $this->model->getStateList());
        $fyw = $this->auth->check('aps/mainprocess/fyw');
        $this->assignconfig('fyw', $this->auth->check('aps/mainprocess/fyw'));//非业务员
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();

            //生產周期
            foreach ($list as &$row) {
                $sczq = \app\admin\model\aps\Procedure::where('mainprocess_id', $row['id'])->sum('maxhours');
                $sczq = intval($sczq / 8) + 1;
                $row['sczq'] = $sczq + $row['lydays'];
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }

                    //不能重复添加相同的主制程名
                    $mpnum = $this->model->where('name', $params['name'])->count();
                    if ($mpnum > 0) {
                        $this->error('不能重复添加相同的主制程名!');
                    }

                    //加入主制程
                    $params['manhours'] = intval($params['procedure1_manhours']) + intval($params['procedure2_manhours']) + intval($params['procedure3_manhours'])
                        + intval($params['procedure4_manhours']) + intval($params['procedure5_manhours']) + intval($params['procedure6_manhours'])
                        + intval($params['procedure7_manhours'])+ intval($params['procedure8_manhours']);
                    $result = $this->model->allowField(true)->save($params);
                    $mainprocess_id = $this->model->id;
                    $params['mainprocess_id'] = $mainprocess_id;

                    //加入工单
                    $this->add2procedure($params);

                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    function add2procedure($params) {

        if ($params && isset($params['mainprocess_id'])) {
            $typelist = \app\admin\model\aps\Devicetype::all();

            $procedures = [];
            $procedures[] = array('id' => $params['devicetype1_id'], 'manhours' => $params['procedure1_manhours']);
            $procedures[] = array('id' => $params['devicetype2_id'], 'manhours' => $params['procedure2_manhours']);
            $procedures[] = array('id' => $params['devicetype3_id'], 'manhours' => $params['procedure3_manhours']);
            $procedures[] = array('id' => $params['devicetype4_id'], 'manhours' => $params['procedure4_manhours']);
            $procedures[] = array('id' => $params['devicetype5_id'], 'manhours' => $params['procedure5_manhours']);
            $procedures[] = array('id' => $params['devicetype6_id'], 'manhours' => $params['procedure6_manhours']);
            $procedures[] = array('id' => $params['devicetype7_id'], 'manhours' => $params['procedure7_manhours']);
            $procedures[] = array('id' => $params['devicetype8_id'], 'manhours' => $params['procedure8_manhours']);

            foreach ($procedures as $row) {
                if (intval($row['id']) == 0) {
                    continue;
                }

                $params['procedure1_id'] = $row['id'];
                $params['procedure1_manhours'] = $row['manhours'];
                $prmodel = new \app\admin\model\aps\Procedure;
                $prmodel->devicetype_id = $row['id'];
                $prmodel->mainprocess_id = $params['mainprocess_id'];
                $prmodel->manhours = $row['manhours'];

                foreach ($typelist as $type) {
                    if ($type['id'] == $row['id']) {
                        $prmodel->name = $type['name'];
                        break;
                    }
                }
                $prmodel->save();
            }
        }

    }

    public function gstj($ids)
    {
        $sql = "SELECT s.id, s.workorder_id, s.mainprocess_id, s.procedure_id,
MAX(s.procedure_manhours) AS MaxManhours,
ROUND(AVG(s.procedure_manhours),4) AS AVGManhours,
MIN(s.procedure_manhours) AS MinManhours,
PD.name as procedurename,
m.name as mainprocessname
FROM fa_aps_statistics s
left join fa_aps_procedure PD ON PD.id  = s.procedure_id
left join fa_aps_mainprocess m ON m.id  = s.mainprocess_id
left join fa_aps_devicetype t ON t.id  = PD.devicetype_id
WHERE s.procedure_manhours > 0 and s.mainprocess_id = {$ids}
GROUP BY s.procedure_id";//执行插入操作

//        $sql = "SELECT s.id, s.workorder_id, s.mainprocess_id, s.procedure_id,
//MAX(s.procedure_manhours) AS MaxManhours,
//ROUND(AVG(s.procedure_manhours),4) AS AVGManhours,
//MIN(s.procedure_manhours) AS MinManhours,
//PD.name as procedurename,
//m.name as mainprocessname
//FROM fa_aps_statistics s
//left join fa_aps_procedure PD ON PD.id  = s.procedure_id
//left join fa_aps_mainprocess m ON m.id  = s.mainprocess_id
//GROUP BY mainprocess_id, procedure_id";//执行插入操作

        $list = Db::query($sql);

        $this->view->assign("list", $list);

        return $this->view->fetch();
    }

    //產品交期預估
    public function cpjqyg($ids)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));


        $list = \app\admin\model\aps\Procedure::where('mainprocess_id', $row->id)->select();
        $maxhours = 0;
        foreach ($list as $row0) {
            $maxhours += floatval($row0->maxhours);
        }

        $row['maxhours'] =  $maxhours + 1;
        $this->view->assign("row", $row);

        return $this->view->fetch();
    }





}
